/*
 Copyright 2007 Ole Rogeberg

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package org.lifeyears.model;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.OrderBy;
import org.hibernate.validator.Email;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotEmpty;

// The table should not be named "user" as this may cause problems for some DBMS
@Table( name = "usertable", uniqueConstraints = @UniqueConstraint( columnNames = { "email" } ) )
@Entity
/**
 * An entity representing a user in the system
 * 
 * @author Aleksander Blomskøld
 */
public class User
    extends AbstractEternalEntity
{

    @Email
    @Length( max = 100 )
    @NotEmpty
    private String email;

    @Length( max = 100 )
    @NotEmpty
    private String name;

    @NotEmpty
    @Length( min = 40, max = 40 )
    private String password;

    @OneToMany(mappedBy="user")
    @OrderBy(clause = "creationDate DESC")
    private List<Donation> donations;

    @Embedded
    private Address address = new Address();

    public Address getAddress()
    {
        return address;
    }

    public void setAddress( final Address address )
    {
        this.address = address;
    }

    public List<Donation> getDonations()
    {
        return donations;
    }

    public void setDonations( List<Donation> donations )
    {
        this.donations = donations;
    }

    public String getEmail()
    {
        return email;
    }

    public void setEmail( final String email )
    {
        this.email = email;
    }

    public String getName()
    {
        return name;
    }

    public void setName( final String name )
    {
        this.name = name;
    }

    public String getPassword()
    {
        return password;
    }

    // setter for Hibernate
    private void setPassword( final String password )
    {
        this.password = password;
    }

    public void hashAndSetPassword( final String password )
    {

        // convert the string to a byte-stream

        setPassword( getHashedPassword( password ) );

    }

    public static String getHashedPassword( final String password )
    {
        // convert the string to a byte-stream
        byte[] digest = null;
        try
        {
            // get the password-string as bytes
            final byte[] bytes = password.getBytes( "UTF-8" );
            final MessageDigest messageDigest = MessageDigest.getInstance( "SHA-1" );
            // get the hash as a byte array
            digest = messageDigest.digest( bytes );
        }
        catch ( final UnsupportedEncodingException e )
        {
            throw new RuntimeException( e );
        }
        catch ( final NoSuchAlgorithmException e )
        {
            e.printStackTrace();
            throw new RuntimeException( e );
        }

        // convert it to a hex-string
        final StringBuilder hexString = new StringBuilder();
        for ( final byte element : digest )
        {
            final String hex = Integer.toHexString( 0xFF & element );
            if ( hex.length() == 1 )
            {
                hexString.append( "0" + hex );
            }
            else
            {
                hexString.append( hex );
            }
        }

        return (hexString.toString());
    }

}
